import redis

class RedisCache:
    def __init__(self):
        # 连接本地redis服务
        self.dbHost = '127.0.0.1'
        # 使用连接池管理对redis server所有的连接，避免每次连接建立、释放的开销
        pool = redis.ConnectionPool(host=self.dbHost, port=6379, decode_responses=True)
        self.r = redis.Redis(connection_pool=pool)

        bPool = redis.ConnectionPool(host=self.dbHost, port=6379, decode_responses=False)
        self.br = redis.Redis(connection_pool=bPool)

        # 超时时间，单位是秒
        # 86400为一天
        # 设置为一周过期时间
        self.ExpireTime = 86400 * 7

    def getBinaryData(self, key):
        if self.br.exists(key):
            self.br.expire(key, time=self.ExpireTime) # 设置过期时间
            return self.br.get(key)
        else:
            return None

    def setBinaryData(self, key, value):
        self.br.set(key, value)
        self.br.expire(key, time=self.ExpireTime) # 设置过期时间

    def getTextData(self, key):
        if self.r.exists(key):
            self.r.expire(key, time=self.ExpireTime)
            return self.r.get(key)
        else:
            return None

    def setTextData(self, key, value):
        self.r.set(key, value)
        self.r.expire(key, time=self.ExpireTime)

    def setSlpkData(self, key, path, mimetype, ziptype):
        self.br.hset(key, 'path', path)
        self.br.hset(key, 'mimetype', mimetype)
        self.br.hset(key, 'ziptype', ziptype)

    def getSlpkData(self, key):
        if self.br.exists(key):
            self.br.expire(key, time=self.ExpireTime)
            return self.br.hget(key, 'path'), self.br.hget(key, 'mimetype').decode('utf-8'), self.br.hget(key,
                                                                                                          'ziptype').decode(
                'utf-8')
        else:
            return None, None, None
